import Kingfisher
import SegmentedPicker
import SwiftUI
import SwiftUIScrollOffset

struct StoreDetailView: View {
    
    var storeId: Int
    
    @State private var detailModel: FoodStoreItemModel!
    @State var selectedIndex: Int? = 0
    
    @Environment(Router.self) private var router
    @Environment(PopupModel.self) private var popup
    @Environment(IndicatorModel.self) private var indicator
    /// 读取设置id的为AAA的scroll view的内容滚动距离
    @ScrollOffset(.top, id: "AAA") private var scrollOffset
    
    private let titleTyps = ["菜品", "商家"]
    /// 滚动铆点，判断自定义导航栏显示与否，滚动图片的高度
    private let scrollPoints: CGFloat = 250.0
    
    
    private var showCustomNavigationBar: Bool {
        -scrollOffset > scrollPoints
    }

    var body: some View {
        ScrollView {
            if detailModel != nil {
                VStack(spacing: 16.0) {
                    // 商铺信息
                    VStack(alignment: .leading, spacing: 12.0) {
                        StoreInfoView(model: detailModel, showRightIcon: false)
                        HStack(spacing: 12.0) {
                            HStack(spacing: 6) {
                                Text("营业时间")
                                    .font(.alibabaPuHuiTi(size: 14.0, weight: .semiBold))
                                    .foregroundStyle(Color.fs020000)
                                Text(detailModel.openTime)
                                    .font(.inter(size: 14.0, weight: .regular))
                                    .foregroundStyle(Color.fs575958)
                            }
                            HStack(spacing: 6) {
                                Text("人均价格")
                                    .font(.alibabaPuHuiTi(size: 14.0, weight: .semiBold))
                                    .foregroundStyle(Color.fs020000)
                                Text(detailModel.prPrice)
                                    .font(.inter(size: 14.0, weight: .regular))
                                    .foregroundStyle(Color.fsFB5D3B)
                                    .lineLimit(1)
                            }
                        }
                        Color.fs000000.opacity(0.07)
                            .frame(height: 1.0)
                        HStack(spacing: 12.0) {
                            VStack(alignment: .leading, spacing: 4.0) {
                                Text("商圈地点")
                                    .font(.alibabaPuHuiTi(size: 14.0, weight: .semiBold))
                                    .foregroundStyle(.fs020000)
                                Text(detailModel.address)
                                    .font(.alibabaPuHuiTi(size: 14.0, weight: .semiBold))
                                    .foregroundStyle(.fs9C9C9C)
                            }
                            Spacer()
                            Link(destination: URL(string: detailModel.mapUrl)!) {
                                VStack {
                                    Image(.iconNavigation)
                                    Text("导航")
                                        .font(.alibabaPuHuiTi(size: 12.0, weight: .regular))
                                        .foregroundStyle(Color.fs020000)
                                }
                            }
                            Link(destination: URL(string: "tel:// \(detailModel.phoneNum)")!) {
                                VStack {
                                    Image(.iconPhone)
                                    Text("电话")
                                        .font(.alibabaPuHuiTi(size: 12.0, weight: .regular))
                                        .foregroundStyle(Color.fs020000)
                                }
                            }
                        }
                    }
                    .padding(12.0)
                    .background(
                        RoundedRectangle(cornerRadius: 16.0)
                            .fill(Color.fsFFFFFF)
                    )
                    .padding(.horizontal, 12.0)
                    
                    if !showCustomNavigationBar {
                        segmentedPicker()
                    }
                    
                    switch selectedIndex {
                    case 0:
                        // 美食列表
                        FoodListView(storeId: storeId)
                            .padding(.horizontal, 12.0)
                    case 1:
                        // 商家
                        StoreCardView(storeDetail: detailModel)
                            .padding(.horizontal, 12.0)
                    default:
                        EmptyView()
                    }
                }
                .padding(.top, 167)
                .background(alignment: .top) {
                    // 轮播
                    AutoLoopCarouselView(images: detailModel.scrollImgUrls, height: scrollPoints)
                }
            } else {
                Color.fsF5F5F5
            }
        }
        .scrollOffsetID("AAA")
        .ignoresSafeArea(.container, edges: .top)
        .background(Color.fsF5F5F5)
        .overlay(alignment: .top) {
            if detailModel != nil {
                VStack(spacing: 0) {
                    HStack(alignment: .center) {
                        // 后退
                        RoundBackButton(bgColor: showCustomNavigationBar ? .gray : .white)
                            .padding(.leading, 12.0)
                            .padding(.vertical, 8.0)
                        Spacer(minLength: 4.0)
                    }
                    .overlay(alignment: .center) {
                        if showCustomNavigationBar {
                            Text(detailModel.title)
    //                        Text("\(scrollOffset)")
                                .font(.alibabaPuHuiTi(size: 16.0, weight: .semiBold))
                                .foregroundStyle(Color.fs020000)
                                .lineLimit(1)
                        }
                    }
                    
                    if showCustomNavigationBar {
                        segmentedPicker()
                    }
                }
                .background(Color.fsFFFFFF.opacity(showCustomNavigationBar ? 1 : 0))
            }
        }
        .navigationBarHidden(true)
        .animation(.easeInOut(duration: 0.3), value: showCustomNavigationBar)
        .task {
            await getStoreDetail()
        }
    }
    
    private func safeTopPadding() -> CGFloat {
        if let top = UIApplication.shared.windows.first?.safeAreaInsets.top {
            return top
        } else {
            return 8
        }
    }
    
    private func segmentedPicker() -> some View {
        // 页面分类
        SegmentedPicker(
            titleTyps,
            selectedIndex: $selectedIndex,
            content: { item, _ in
                Text(item)
                    .font(.alibabaPuHuiTi(size: 16.0, weight: .semiBold))
                    .foregroundColor(Color.fs020000)
                    .padding(.vertical, 11)
                    .frame(maxWidth: .infinity)
            },
            selection: {
                Capsule()
                    .fill(Color.fsFFC600)
            }
        )
//        .onAppear {
//            selectedIndex = 0
//        }
        .animation(.easeInOut(duration: 0.3), value: selectedIndex)
        .frame(maxWidth: .infinity)
        .padding(4.0)
        .background(
            Capsule().fill(Color.fsFFFFFF)
        )
        .padding(.horizontal, 12.0)
    }
    
    // MARK: - 获取详情
    
    private func getStoreDetail() async {
        let target = API.shopDetail(id: storeId)
        do {
            indicator.show(content: .loading)
            let model = try await NetworkManager.shared.request(target, responseType: FoodStoreDetailRespModel.self)
            detailModel = FoodStoreItemModel(respModel: model.data)
            indicator.hide()
        } catch {
            indicator.hide()
            if let error = error as? BaseError {
                popup.show(content: error.message)
            }
        }
    }
    
    
}
